import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { SpliceDate } from "@/utils/public/method"
import { ref, reactive, nextTick, watch, onMounted, computed } from "vue";
import {
  ProProtectionGetPType,
  ProProtectionGetProject,
  ProProtectionGetProProducts,
  ProProtectionAddProProducts
} from "@/api/stu/InsuranceData"
import qs from "qs";
export function useBUnderwritingPricing() {
  const route = useRoute()
  const dataList = ref();
  const Refstubim_from = ref();
  const RefAddInsuranceForm = ref()
  const loading = ref<boolean>(false);
  const btnloading = ref<boolean>(false);
  const DialogVisible = ref(false);
  const SecurityItemVisible = ref(false);
  const insDisabled = ref(false);
  const columns = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "保险产品名称",
      prop: "ppName",
    }, {
      label: "保险类型",
      prop: "pType",
    }, {
      label: "创建时间",
      prop: "createTime",
      cellRenderer: ({ row }) => (
        SpliceDate(row.createTime)
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 30,
    currentPage: 1,
    pageSizes: [5, 10, 30],
    background: true
  });
  const dataList2 = ref([]);
  const loading2 = ref(false);
  const columns2 = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "保障项目",
      prop: "projectName",
    },
    {
      label: "保险范围",
      prop: "range",
    },
    {
      label: "保障金额",
      prop: "price",
    },
    {
      label: "操作",
      fixed: "right",
      width: 120,
      slot: "operation"
    }
  ];
  const rules = {
    insuranceName: [
      {
        required: true,
        message: '请输入保险产品名称',
        trigger: 'blur',
      }, {
        required: true,
        message: '请输入5-20个汉字的保险产品名称',
        trigger: 'change',
        min: 5,
        max: 20
      }
    ],
    insuranceType: [
      {
        required: true,
        message: '请选择保险类型',
        trigger: 'blur',
      }
    ],
    createDate: [
      {
        required: true,
        message: '请选择时间',
        trigger: 'blur',
      }
    ],
    insuranceOutTime: [
      {
        required: true,
        message: '请选择保险期限',
        trigger: 'blur',
      }
    ]
  }
  const AddRules = {
    SecurityItem: [
      {
        required: true,
        message: '请选择保障项目',
        trigger: 'blur',
      }
    ],
    InsuranceCoverage: [
      {
        required: true,
        message: '请选择保险范围',
        trigger: 'blur',
      }
    ],
    PremiumOption: [
      {
        required: true,
        message: '请选择保额选项',
        trigger: 'blur',
      }
    ],
  }
  const MInsuranceCoverage = ref();//保存保险范围的id
  const SeleteInsuranceType = ref([]);//一级选择保险类型
  const SeleteSecurityItem = ref();// 二级选择保障项目
  const SeleteInsuranceCoverage = ref();// 三级选择保险范围
  const SeletePremiumOption = ref();//保额选项
  const isinsuranceOutTime = ref(false);// 保险类型是否为车险
  const insuranceForm = reactive<any>({
    insuranceName: "",
    createDate: "",
    insuranceType: "",
    insuranceOutTime: "",
    insuranceList: []
  })

  const AddInsuranceForm = reactive<any>({
    SecurityItem: "",
    InsuranceCoverage: "",
    PremiumOption: ""
  });
  // 保险设计
  async function InsuranceData() {
    DialogVisible.value = true;
    const res = await ProProtectionGetPType();
    if (res.success) {
      SeleteInsuranceType.value = res.data;
    } else {
      ElMessage.error(res.msg)
    }
  }
  // 查看详情
  async function ViewDetails(row) {
    const data = {
      ppId: row.ppId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize
    };
    const res = await ProProtectionGetProject(data);
    if (res.success) {
      insDisabled.value = true;
      DialogVisible.value = true;
      nextTick(() => {
        insuranceForm.createDate = row.createTime;
        insuranceForm.insuranceName = row.ppName;
        insuranceForm.insuranceType = row.pType;
        insuranceForm.insuranceOutTime = row.pTime;
        dataList2.value = res.data;
      })
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 删除
  async function DeleteDetails(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      // 确定
      dataList2.value = dataList2.value.filter((el) => {
        return el.rangeId !== row.rangeId
      });
    }).catch(() => { })
  }

  // 添加保障项目列表
  function AddInsuranceList() {
    SecurityItemVisible.value = true
  }

  // 选择保险类型
  function changeinsuranceType(row) {
    // console.log("选择保险类型", row);
    if (row.typeName === '车险') {
      insuranceForm.insuranceOutTime = '一年';
      isinsuranceOutTime.value = true;
    } else {
      insuranceForm.insuranceOutTime = '';
      isinsuranceOutTime.value = false;
    }
    SeleteSecurityItem.value = row.children;
  }
  // 选择保障项目
  function changeSeleteSecurityItem(row) {
    // console.log("选择保障项目", row);
    // 查看选中的列表是否有保障项目
    const arry = []
    row.children.forEach(l => {
      // 列表无数据时全部可选
      if (!dataList2.value.length) {
        l.isDelete = false
      } else {
        dataList2.value.forEach(item => {
          arry.push(item.range)
          const arrys = Array.from(new Set(arry));
          // TOD 列表删除后将状态改为可继续勾选
          if (arrys.includes(l.typeName)) l.isDelete = true;
          else l.isDelete = false;
        })
      }
    })

    SeleteInsuranceCoverage.value = row.children;
    SeletePremiumOption.value = []
    AddInsuranceForm.InsuranceCoverage = "";
    AddInsuranceForm.PremiumOption = "";
  }
  //保险范围
  function changeInsuranceCoverage(state, row) {
    if (state) return;
    MInsuranceCoverage.value = row;
    SeletePremiumOption.value = row.children;
    AddInsuranceForm.PremiumOption = "";
    const isArry = ['财产损失', '意外身故伤残', '意外医疗', '乘客人身伤亡'];
    if (isArry.includes(row.typeValue)) {
      AddInsuranceForm.PremiumOption = row.children
    } else {
      AddInsuranceForm.PremiumOption = "";
    }
  }
  // 提交产品信息
  function StubimRefAddInsuranceForm(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      // TODO:将已选的保障项目 isDelete值设为true
      // SeleteInsuranceType.value.forEach((r) => {
      //   return r.children.forEach((e) => {
      //     return e.children.map((k) => {
      //       if (k.typeId === MInsuranceCoverage.value.typeId) {
      //         return k.isDelete = true
      //       }
      //     })
      //   })
      // })

      SeleteInsuranceType.value.forEach(r => {
        r.children.forEach(e => {
          e.children.filter(k => k.typeId === MInsuranceCoverage.value.typeId)
            .forEach(k => k.isDelete = true);
        });
      });

      const arr = AddInsuranceForm.PremiumOption.map(el => el);
      arr.forEach((el) => {
        dataList2.value.push({
          projectNameId: insuranceForm.insuranceType.typeId,
          projectName: AddInsuranceForm.SecurityItem.typeValue,
          rangeId: el.typeId,
          range: AddInsuranceForm.InsuranceCoverage.typeValue,
          price: el.typeValue,
          priceId: el.typeId
        })
      });
      closeRefAddInsuranceForm(row)
    })
  };

  // 关闭产品信息并清空
  function closeRefAddInsuranceForm(row: FormInstance | undefined) {
    SecurityItemVisible.value = false;
    SeleteInsuranceCoverage.value = [];
    SeletePremiumOption.value = [];
    AddInsuranceForm.PremiumOption = ""
    row.resetFields();
  }

  // 提交整个保险设计
  function stubim_from(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      if (!dataList2.value.length) {
        ElMessage.warning('请添加保险内容')
        return
      };
      btnloading.value = true;
      const data = {
        PlanId: route.query.planId,
        TaskId: route.query.taskId,
        ppName: insuranceForm.insuranceName,
        ptId: insuranceForm.insuranceType.typeId,
        pTime: insuranceForm.insuranceOutTime,
        createTime: insuranceForm.createDate,
        pType: insuranceForm.insuranceType.typeValue,
        guarProjectList: dataList2.value
      };
      const res = await ProProtectionAddProProducts(data);
      if (res.success) {
        ElMessage.success(res.msg)
        getDataList();
        btnloading.value = false;
        close_from(row)
      } else {
        ElMessage.error(res.msg);
        setTimeout(() => { btnloading.value = false; }, 1500)
      }
    }
    )
  }

  // 关闭
  function close_from(row: FormInstance | undefined) {
    insuranceForm.insuranceType = ""
    isinsuranceOutTime.value = false;
    DialogVisible.value = false;
    insDisabled.value = false;
    insuranceForm.createDate = "";
    insuranceForm.insuranceName = "";
    insuranceForm.insuranceType = "";
    insuranceForm.insuranceOutTime = "";
    dataList2.value = [];
    row.resetFields();
  }

  function handleSizeChange(val) {
    getDataList()
  }

  function handleCurrentChange(val) {
    getDataList()
  }

  async function getDataList() {
    const data = {
      "taskId": route.query.taskId,
      "planId": route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize
    }
    const res = await ProProtectionGetProProducts(data);
    if (res.success) {
      dataList.value = res?.data?.items;
      pagination.total = res?.data?.totalCount;
    } else {
      ElMessage.error(res.msg)
    }
  }

  onMounted(() => {
    getDataList()
  })

  return {
    rules,
    columns,
    loading,
    AddRules,
    dataList,
    columns2,
    loading2,
    dataList2,
    btnloading,
    pagination,
    insDisabled,
    DialogVisible,
    insuranceForm,
    Refstubim_from,
    AddInsuranceForm,
    SeleteSecurityItem,
    isinsuranceOutTime,
    SecurityItemVisible,
    SeleteInsuranceType,
    SeletePremiumOption,
    RefAddInsuranceForm,
    SeleteInsuranceCoverage,
    changeInsuranceCoverage,
    changeSeleteSecurityItem,
    StubimRefAddInsuranceForm,
    closeRefAddInsuranceForm,
    handleCurrentChange,
    changeinsuranceType,
    AddInsuranceList,
    handleSizeChange,
    stubim_from,
    ViewDetails,
    InsuranceData,
    DeleteDetails,
    close_from
  }
}
